package ktwl.code.connection;

import java.sql.*;

/**
 * jdbc连接
 *
 * @author zhuhe on 2019/8/21 14:54
 * @version 1.0
 */
public class JdbcConnection {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
      * 数据库相关信息初始化 on 2019/8/26 17:34
      *
      * @param driver 驱动
      * @param url 连接地址
      * @param username 用户名
      * @param password 密码
      */
    public static void init(String driver,String url,String username,String password){
        setDriver(driver == null || "".equals(driver)?"com.mysql.cj.jdbc.Driver":driver);
        setUrl(url);
        setUsername(username);
        setPassword(password);
    }

    /**
     * 获取连接方法
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放资源方法
     *
     * @param conn conn
     * @param pstmt pstmt
     * @param rs rs
     */
    public static void release(Connection conn, PreparedStatement pstmt,Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public static String getDriver() {
        return driver;
    }

    public static void setDriver(String driver) {
        JdbcConnection.driver = driver;
    }

    public static String getUrl() {
        return url;
    }

    public static void setUrl(String url) {
        JdbcConnection.url = url;
    }

    public static String getUsername() {
        return username;
    }

    public static void setUsername(String username) {
        JdbcConnection.username = username;
    }

    public static String getPassword() {
        return password;
    }

    public static void setPassword(String password) {
        JdbcConnection.password = password;
    }

}